package cn.javase.concurrent._并发编程._04_共享模型之管程._synchronized;

import java.util.ArrayList;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

@Slf4j
public class _卖票练习 {

    /**
     * n个售票窗口，共m张票
     */
    private int ticket = 100;                    // 票数
    private final int WINDOW_NUM = 17;           // 窗口数

    @Test
    public void test() throws InterruptedException {
        ArrayList<Thread> list = new ArrayList<>(WINDOW_NUM);
        for (int i = 1; i <= WINDOW_NUM; i++) {
            Thread thread = new Thread(() -> {
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    synchronized (this) {
                        if (ticket > 0) {
                            log.info("正在卖倒数第{}张票", ticket);
                            ticket--;
                        } else {
                            break;
                        }
                    }
                }
            }, "窗口" + i);
            list.add(thread);
        }
        for (Thread thread : list) {
            thread.start();
        }
        for (Thread thread : list) {
            thread.join();
        }
        log.info("剩余票数：{}", ticket);
    }

}
